package org.jeecg.modules.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xkcoding.http.HttpUtil;
import com.xkcoding.http.config.HttpConfig;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.SpringContextHolder;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.base.service.impl.BaseCommonServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
@Slf4j
@Component
public class HttpClientUtil {

    private static BaseCommonService baseCommonService;

    @Autowired
    public HttpClientUtil(BaseCommonService baseCommonService) {
        HttpClientUtil.baseCommonService = baseCommonService;
    }

    public static JSONObject sendGet(String url, Map<String, String> paramsMap) {
        String resultStr ="";
        boolean result = true;
        try {
            log.info("GET请求:{}", url);
            log.info("GET请求 参数:{}", JSONObject.toJSONString(paramsMap));
            HttpConfig httpConfig = new HttpConfig();
            httpConfig.setTimeout(500000);
            HttpUtil.setConfig(httpConfig);
            resultStr = HttpUtil.get(url, paramsMap, false);
            log.info("GET请求 请求结果:{}", resultStr);
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        String logContent = "[api]-GET请求:" + url+ "<br/>参数JSON" + JSONObject.toJSONString(paramsMap);
        baseCommonService.addLog(logContent, CommonConstant.LOG_TYPE_2, 2);
        if(!result){
            return null;
        }
        return JSON.parseObject(resultStr);
    }
    public static JSONObject sendPost(String url, Map<String, Object> paramsMap) {
        String resultStr ="";
        boolean result = true;
        try {
            log.info("POST请求:{}", url);
            log.info("POST请求 参数:{}", JSONObject.toJSONString(paramsMap));
            HttpConfig httpConfig = new HttpConfig();
            httpConfig.setTimeout(500000);
            HttpUtil.setConfig(httpConfig);
            resultStr = HttpUtil.post(url, JSONObject.toJSONString(paramsMap), null);
            System.out.println("请求结果:" + resultStr);
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        String logContent = "[api]-POST请求:" + url+ "<br/>参数JSON" + JSONObject.toJSONString(paramsMap) +"<br/>请求结果:"+resultStr;
        baseCommonService.addLog(logContent, CommonConstant.LOG_TYPE_2, 2);
        if(!result){
            return null;
        }
        return JSON.parseObject(resultStr);
    }
}
